<?php
// +----------------------------------------------------------------------
// | Longbing [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright Chengdu longbing Technology Co., Ltd.
// +----------------------------------------------------------------------
// | Website http://longbing.org/
// +----------------------------------------------------------------------
// | Sales manager: +86-13558882532 / +86-13330887474
// | Technical support: +86-15680635005
// | After-sale service: +86-17361005938
// +----------------------------------------------------------------------

declare(strict_types=1);

namespace app\im\service;


use app\Common\LongbingServiceNotice;
use app\Common\model\LongbingUserInfo;
use app\Common\service\LongbingUserInfoService;
use app\Common\service\LongbingUserService;
use app\im\model\ImChat;
use app\im\model\ImMessage;
use app\publics\model\TmplConfig;
use longbingcore\tools\LongbingTime;
use longbingcore\wxcore\WxTmpl;

class ImService
{

    /**
     * @param $data
     * @功能说明:新增消息
     * @author jingshuixian
     * @DataTime: 2020/1/13 17:01
     */
    public static function addMessage($data){


        //存储消息
        $message_model = new ImMessage();
        $result  = $message_model->insertGetId( $data );
        if($result){
            //修改时间chat
            $chat_model    = new ImChat();
            $chat_model->updateChat(['id' => $data['chat_id']] ,[]);

            //修改朋友表数据
            ImMessageFriendService::updateFriendByMessage($message_model->find($result));


        }

        return $result;


    }

    /**
     * @param $uniacid
     * @param $user_id
     * @param $customer_id
     * @功能说明:获取聊天房间ID
     * @author jingshuixian
     * @DataTime: 2020/1/13 17:01
     */
    public static  function getChatId($uniacid , $user_id ,$target_id )
    {
        $chat_model = new ImChat();

        //查询条件
        $where = [
            ['user_id' , '=' ,$user_id],
            ['target_id' ,'=' , $target_id],
        ];
        $whereOr = [
            ['user_id' , '=' ,$target_id],
            ['target_id' ,'=' , $user_id],
        ];
        $chatId = $chat_model->where(function ($query) use($where, $whereOr){
            $query->whereOr([$where,$whereOr]);
        })
            ->where(['uniacid' => $uniacid ,'deleted' => 0])
            ->field('id as chat_id,user_id,target_id')
            ->value('id');


        if(empty($chatId))
        {
            $chatData= (['user_id' => $user_id ,'target_id' => $target_id ,'uniacid' => $uniacid ,'create_time' => time()]);
            $chatId = $chat_model->createChat($chatData);
        }

        return $chatId;
    }

    /**
     * @param $userId
     * @功能说明:获取未读消息数量
     * @author jingshuixian
     * @DataTime: 2020/1/13 17:22
     */
    public static  function  getUnReadMessageCount($userId){

        $message_model = new ImMessage();
        $count = $message_model->listMessageCount(['target_id' => $userId ,'status' => 1]);

        return $count;
    }

    /**
     * @param $userId
     * @param $target_id
     * @功能说明:根据用户ID和目标用户ID获取未读消息数量
     * @author jingshuixian
     * @DataTime: 2020/1/15 12:10
     */
    public static  function  getUnReadMessageCountByUserIdAndTargetId($userId , $target_id ){

        $message_model = new ImMessage();
        $count = $message_model->listMessageCount(['user_id'=> $userId  ,'target_id' => $target_id ,'status' => 1]);

        return $count;
    }

    /**
     * @param $uniacid
     * @param $chat_id
     * @param $user_id
     * @功能说明: 更新消息未读信息,返回修改数量
     * @author jingshuixian
     * @DataTime: 2020/1/14 9:54
     */
    public static function readMessage($uniacid , $user_id  , $friendId){

        $message_model = new ImMessage();

        $count = $message_model->where([
            ['uniacid' , '=' , $uniacid]  ,
            ['user_id' , '=' , $friendId ] ,
            ['target_id' , '=' , $user_id ]

        ])->update([ 'status' => 2 ]) ;

        //处理未读消息数据
        ImMessageFriendService::readMessage( $uniacid  , $user_id ,  $friendId ) ;


        return $count ;
    }


    /**
     * @param $uniacid
     * @param $userId
     * @param $data
     * @param string $page
     * @功能说明:发送模板消息
     * @author jingshuixian
     * @DataTime: 2020/1/14 13:42
     */
    public static function sendTmplMsg($uniacid , $userId ,$data , $page='' , $tmpl_name = 'im_msg'){

        $openid     = LongbingUserService::getUserOpenId($userId);
        //模版消息model
        $tmpl_model = new TmplConfig();
        //获取模版
        $tmpl       = $tmpl_model->where(['uniacid'=>$uniacid,'tmpl_name'=>$tmpl_name])->find();
        //如果未添加模版消息 则不发送
        if(empty($tmpl)){
            return true;
        }else{
            $tmpl = $tmpl->toArray();
        }
        //模版id
        $tmpl_id = $tmpl['tmpl_id'];

        $service_model = new WxTmpl( $uniacid );

        $key_worlds    = $service_model::getTmplKey($tmpl_id);

        if(!empty($openid)&&!empty($tmpl_id)&&!empty($key_worlds)){
            //发送内容
            $send_data = [];

            foreach ($key_worlds as $key => $item ){

                if(array_key_exists($key -1,$data)){

                    $send_data[$item]['value'] =  $data[$key -1 ] ;
                }
            }
            //模版消息库类
            $tmpl_sever = new WxTmpl($uniacid);
            //发送模版消息
            $res = $tmpl_sever::sendTmpl($openid,$tmpl_id,$send_data,$page);

        }
        return true;
    }

    /**
     * @param $uniacid
     * @param $user_id
     * @param $target_id
     * @功能说明:发送聊天通知信息
     * @author jingshuixian
     * @DataTime: 2020/2/27 11:49
     */
    public static function sendImMessageTmpl($uniacid , $user_id , $target_id , $message = ''){




        if(LongbingUserInfoService::isStraffByUserId($user_id) && !LongbingUserInfoService::isStraffByUserId($target_id)) //发送者是员工并且接收者是普通用户，员工回复消息，通知用户采用订阅消息
        {


            $message = '有未读私信'  ;

            $name= $name = LongbingUserInfoService::getNameByUserId($user_id);


            ImService::sendTmplMsg($uniacid , $target_id , [ $name ,  $message , LongbingTime::getChinaNowTime()]  , 'pages/user/home'  );

        }else //发送者是普通用户,消息接收人是员工
        {


            $count = self::getUnReadMessageCount($target_id);

            $message = '有' . $count .'条未读私信'  ;

            $notice = new LongbingServiceNotice($uniacid);

            $name = LongbingUserService::getUserNickNameOpenId($user_id);

            $notice->sendImMessageServiceNoticeToStaff($target_id ,$message , $name);


        }

    }

}